package ms.zuul;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.context.RequestContext;
import ms.zuul.filter.MsResponseBody;
import ms.zuul.filter.ResponseCode;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.web.DefaultErrorAttributes;
import org.springframework.cloud.client.SpringCloudApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@EnableZuulProxy
@SpringCloudApplication
public class MsZuulApplication {

	/**
	 * 统一将网关层抛出的异常转换成MsResponseBody返回给调用方
	 *
	 * @return
	 */
	@Bean
	public DefaultErrorAttributes errorAttributes() {
		return new DefaultErrorAttributes() {
			@Override
			public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
                Throwable th = super.getError(requestAttributes);

                RequestContext ctx = RequestContext.getCurrentContext();
                ctx.setResponseStatusCode(HttpServletResponse.SC_OK);

                MsResponseBody msResponseBody = new MsResponseBody(ResponseCode.SYSTEM_EXCEPTION, th.getCause().getMessage());

                Map<String, Object> result = JSON.parseObject(JSON.toJSONString(msResponseBody), Map.class);

                return result;
			}
		};
	}
	/**
	 * 允许跨域
	 * @return
	 */
	private CorsConfiguration buildConfig() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		corsConfiguration.addAllowedOrigin("*");
		corsConfiguration.addAllowedHeader("*");
		corsConfiguration.addAllowedMethod("*");
		return corsConfiguration;
	}

	/**
	 * 跨域过滤器
	 * @return
	 */
	@Bean
	public CorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", buildConfig()); // 4
		return new CorsFilter(source);
	}
	public static void main(String[] args) {
		SpringApplication.run(MsZuulApplication.class, args);
	}
}
